package com.ccsc.auth.service.impl;

import com.ccsc.auth.dao.ResourceDao;
import com.ccsc.auth.dao.RoleDao;
import com.ccsc.auth.dao.UserDao;
import com.ccsc.auth.entity.*;
import com.ccsc.auth.service.PositionService;
import com.ccsc.auth.service.ResourceService;
import com.ccsc.auth.service.RoleService;
import com.ccsc.auth.service.UserService;
import com.ccsc.auth.utils.DataMap;
import com.ccsc.auth.utils.MD5;
import com.ccsc.auth.utils.Page;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户serviceimpl
 * Created by XingWen on 2016/3/29.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private PositionService positionService;

    @Override
    public User verifyAccount(DataMap params) throws Exception {
        User user=new User();
        user.setAccount((String) params.get("account"));
        user.setPassword((String) params.get("password"));
        User loginUser = userDao.verifyAccount(user);
        return loginUser;
    }

    /**
     *添加用户 包括 部门职位 授权信息
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public Integer createUser(User user) throws Exception {
        //添加个人信息
        if(!Strings.isNullOrEmpty(user.getPassword())){
            user.setPassword(MD5.MD5Encode(user.getPassword()));
        }
        //判断检查的类型 和ip
        if(user.getVerify_type() == 1 && !"".equals(user.getVerify_value())){
            user.setVerify_value("");
        }else if(user.getVerify_type() != 1 && "".equals(user.getVerify_value())){
            throw new Exception("请输入IP段");
        }
        int i=userDao.createUser(user);
        int j=0;
        //添加部门
        for (Map<Department,Position> departmentPositionMap:user.getPositionMap()){
            Map<Department,Position> map = new HashMap<>();
            Iterator iter = departmentPositionMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Department key = (Department) entry.getKey();
                Position val = (Position) entry.getValue();
                val.setDepartment(key);
                //Position g=positionService.getDepartmentAndPosition(val);
                //if(g==null) {
                positionService.createDepartmentAndPosition(val);
                //}
                userDao.createUserAndPosition(user.getId(), val.getRdop_id());
          }
        }
        //添加角色授权
        return userDao.createUserAndRole(user);
    }

    @Override
    public List<User> getAllUsers() throws Exception {
        List<User> userList=userDao.getAllUsers();
        for (User usertemp:userList) {
            //添加角色信息
            usertemp.setRoleList(roleService.getRolesByUserId(usertemp.getId()));
            //添加部门信息
            usertemp.setPositionMap(positionService.getDepartmentAndPositionsByUserId(usertemp.getId()));
        }
        return userList;

    }

    @Override
    public List<User> getUserByStatus(Integer status) throws Exception {
        User user=new User();
        user.setStatus(status);
        return userDao.getUsersByCondition(user);
    }

    @Override
    public List<User> getUserByName(String name) throws Exception {
        User user=new User();
        user.setName(name);
        return userDao.getUsersByCondition(user);
    }

    @Override
    public List<User> getUserByRoleId(Integer roleId) throws Exception {
        List<User> userList=userDao.getUserInfoByRoleId(roleId);
        for (User usertemp:userList) {
            //添加角色信息
            usertemp.setRoleList(roleService.getRolesByUserId(usertemp.getId()));
            //添加部门信息
            usertemp.setPositionMap(positionService.getDepartmentAndPositionsByUserId(usertemp.getId()));
        }
        return userList;
    }

    @Override
    public List<User> getUsersByAccount(String account) throws Exception {
        User user=new User();
        user.setAccount(account);
        return userDao.getUsersByCondition(user);
    }

    @Override
    public List<User> getUserByDepartmentAndPosition(Integer department, Integer position) throws Exception {
        return userDao.getUserInfoByDepartmentOrPosition(department,position);
    }

    @Override
    public Page getUsersByPage(DataMap params) throws Exception {
        //datamap 中roleId 表示角色id，status表示角色状态，keyWord表示关键字
        List<User> resultList=null;
        try {
            resultList = userDao.getAllUsers(params,new PageBounds(params.getInt("page"), params.getInt("pageSize")));

        }catch (Exception e){
            e.printStackTrace();
        }
        for (User usertemp:resultList) {
            //添加角色信息
            usertemp.setRoleList(roleService.getRolesByUserId(usertemp.getId()));
            //添加部门信息
            usertemp.setPositionMap(positionService.getDepartmentAndPositionsByUserId(usertemp.getId()));
        }
        PageList<User> pageList = (PageList<User>) resultList;
        return new Page(pageList);
    }

    @Override
    public Page getUsersByPage(User user, DataMap params) throws Exception {
        List<User> resultList = userDao.getUsersByCondition(user,new PageBounds(params.getInt("page"), params.getInt("pageSize")));
        for (User usertemp:resultList) {
            //添加角色信息
            usertemp.setRoleList(roleService.getRolesByUserId(usertemp.getId()));
            //添加部门信息
            usertemp.setPositionMap(positionService.getDepartmentAndPositionsByUserId(usertemp.getId()));
        }
        PageList<User> pageList = (PageList<User>) resultList;
        return new Page(pageList);
    }

    @Override
    public User getUserById(Integer id) throws Exception {
        User userParam =new User();
        userParam.setId(id);
        User user=userDao.getUserInfoById(userParam);
        if(user==null){return null;}
        //添加角色
        List<Role> roles=roleService.getRolesByUserId(user.getId());
        user.setRoleList(roles);
        //添加部门信息
        user.setPositionMap(positionService.getDepartmentAndPositionsByUserId(user.getId()));
        //添加资源列表
        user.setResourceList(resourceService.getResourcelistByRolelist(roles));
        return user;
    }

    @Override
    public User getUserByAccount(String account) throws Exception {
        User user=new User();
        user.setAccount(account);
        return userDao.verifyAccount(user);
    }

    @Override
    public Integer updateUser(User user) throws Exception {
        //判断检查的类型 和ip
        if(user.getVerify_type() == 1 && !"".equals(user.getVerify_value())){
            user.setVerify_value("");
        }else if(user.getVerify_type() != 1 && "".equals(user.getVerify_value())){
            throw new Exception("请输入IP段");
        }
        //需要修改 部门角色信息
        Map<Department,Position> departmentPositionMap=user.getPositionMap().get(0);
        Position position=null;
        //遍历map
        Iterator iter = departmentPositionMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Department key = (Department) entry.getKey();
            position = (Position) entry.getValue();
            position.setDepartment(key);
            if(position.getRdop_id()!=null){
                positionService.updateDepartmentAndPosition(position);
            }
        }
        DataMap dataMap=new DataMap();
        dataMap.put("user",user);
        dataMap.put("roleId", null);
        userDao.deleteUserAndRole(dataMap);
        userDao.createUserAndRole(user);
        positionService.updateDepartmentAndPosition(position);
        if(!Strings.isNullOrEmpty(user.getPassword())){
            user.setPassword(MD5.MD5Encode(user.getPassword()));
        }
        return userDao.updateUser(user);
    }

    @Override
    public Integer deleteUserById(Integer id) throws Exception {
        User user=new User();
        user.setId(id);
        //删除用户的所有部门职位
        int i = userDao.deleteUserAndPosition(user.getId(),null,null);
        DataMap params = new DataMap();
        params.put("user", user);
        params.put("roleId", null);
        //删除用户的所有角色信息
        int j=userDao.deleteUserAndRole(params);
        //删除用户的个人信息
        int k=userDao.deleteUser(user);
        return i&j&k;
    }

    @Override
    public Integer activeUser(Integer id) throws Exception {
        User user=new User();
        user.setId(id);
        user.setStatus(1);
        return userDao.updateUser(user);
    }

    @Override
    public Integer withdrawUser(Integer id) throws Exception {
        User user=new User();
        user.setId(id);
        user.setStatus(0);
        return userDao.updateUser(user);
    }

    @Override
    public Integer batchActiveUser(List<Integer> ids) throws Exception {
        int result=0;
        for (Integer id:ids) {
            result=activeUser(id);
        }
        return result;
    }

    @Override
    public Integer batchWithdrawUser(List<Integer> ids) throws Exception {
        int result=0;
        for (Integer id:ids) {
            result=withdrawUser(id);
        }
        return result;
    }
}
